package com.cool.controller;

import com.cool.dao.AdminMapper;
import com.cool.entity.Admin;
import com.cool.util.Encryption;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping(value = "/api/admin")
public class AdminController {
    @Autowired
    private AdminMapper adminMapper;

    @RequestMapping(method = RequestMethod.GET,produces = "application/json;charset=utf-8")
    public ResponseEntity<Admin> login(@RequestParam(value = "name")String name,@RequestParam(value = "pwd")String pwd){
        Admin admin=new Admin();
        admin.setName(name);
        admin.setPwd(pwd);
        if(adminMapper.selectByPrimaryKey(admin.getName())==null){
            return new ResponseEntity<Admin>(HttpStatus.NO_CONTENT);
        }
        pwd= Encryption.MD5(admin.getPwd());
        admin.setPwd(pwd);
        Admin result=adminMapper.selectByAll(admin);
        if(result==null){
            return new ResponseEntity<Admin>(HttpStatus.FORBIDDEN);
        }
        result.setPwd(null);
        return new ResponseEntity<Admin>(result,HttpStatus.OK);
    }

    @RequestMapping(method =RequestMethod.POST,consumes = "application/json;charset=utf-8",produces = "application/json;charset=utf-8")
    public ResponseEntity<Admin> add(@RequestBody Admin admin){
        if(adminMapper.selectByPrimaryKey(admin.getName())!=null){
            return new ResponseEntity<Admin>(HttpStatus.FORBIDDEN);
        }
        String pwd=Encryption.MD5(admin.getPwd());
        admin.setPwd(pwd);
        adminMapper.insert(admin);
        admin.setPwd(null);
        return new ResponseEntity<Admin>(admin,HttpStatus.CREATED);
    }

    @RequestMapping(value = "/{name}",method = RequestMethod.DELETE,produces = "application/json;charset=utf-8")
    public ResponseEntity<Admin> del(@PathVariable String name)
    {
        if(adminMapper.selectByPrimaryKey(name)==null){
            return new ResponseEntity<Admin>(HttpStatus.NO_CONTENT);
        }
        adminMapper.deleteByPrimaryKey(name);
        return new ResponseEntity<Admin>(HttpStatus.OK);
    }

    @RequestMapping(method = RequestMethod.PUT,consumes = "application/json;charset=utf-8",produces = "application/json;charset=utf-8")
    public ResponseEntity<Admin> update(@RequestBody Admin admin){
        if(adminMapper.selectByPrimaryKey(admin.getName())==null){
            return new ResponseEntity<Admin>(HttpStatus.NO_CONTENT);
        }
        String pwd=Encryption.MD5(admin.getPwd());
        admin.setPwd(pwd);
        adminMapper.updateByPrimaryKey(admin);
        Admin result=adminMapper.selectByPrimaryKey(admin.getName());
        result.setPwd(null);
        return new ResponseEntity<Admin>(result,HttpStatus.OK);
    }

}
